#pragma once
#include <iostream>
#include <cstring>
#include <string>
#include <sys/select.h>
#include "sock.hpp"
#include "log.hpp"
#include "err.hpp"

const static int gport = 8888;

class SelectServer{
public:
    SelectServer(uint16_t port = gport):_port(port){

    }
    void Init(){
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();
    }

    void Start(){
        //在网络中，新链接的到来被当做读事件就绪

        //创建读fd集合
        fd_set rfds;
        //清空集合
        FD_ZERO(&rfds);
        //将_listensock添加到读fd集合
        FD_SET(_listensock.Fd(), &rfds);
        
        while(1){
            struct timeval timeout = {2, 0};
            int n = select(_listensock.Fd() + 1, &rfds, nullptr, nullptr, &timeout);
            switch (n){
                case 0:
                    logMessage(DEBUG, "time out, %d:%s", errno, strerror(errno));
                    break;
                case -1:
                    logMessage(WARNING, "%d:%s", errno, strerror(errno));
                    break;
                default:
                    logMessage(DEBUG, "有一个就绪事件发生");
                    break;
            }  
        }

    }

    ~SelectServer(){
        _listensock.Close();
    }

private:
    uint16_t _port;
    Sock _listensock;
};



